﻿/// <summary>
/// data   :2016-04-27
/// author :fanzhengyong
/// 渐变字体组件
/// 1、直接拖到包含Text组件的父对象上或者从组件菜单上添加
/// 2、参数
///    topColor    上半部颜色
///    bottomColor 下半部颜色
/// </summary>
/// 
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;

namespace UEngine
{
    [AddComponentMenu("Custom/UGUI/Gradient")]
    public class Gradient : BaseMeshEffect
    {
        [SerializeField]
        public Color32
            topColor = Color.white;
        [SerializeField]
        public Color32
            bottomColor = Color.black;

        public override void ModifyMesh(VertexHelper vh)
        {

            if (!IsActive())
            {
                return;
            }

            List<UIVertex> vertexList = new List<UIVertex>();
            vh.GetUIVertexStream(vertexList);

            int count = vertexList.Count;
            if (count > 0)
            {
                float bottomY = vertexList[0].position.y;
                float topY = vertexList[0].position.y;

                for (int i = 1; i < count; i++)
                {
                    float y = vertexList[i].position.y;
                    if (y > topY)
                    {
                        topY = y;
                    }
                    else if (y < bottomY)
                    {
                        bottomY = y;
                    }
                }

                UIVertex vertex;
                float uiElementHeight = topY - bottomY;
                for (int i = 0; i < count; i++)
                {
                    vertex = vertexList[i];
                    vertex.color = Color32.Lerp(bottomColor, topColor, (vertex.position.y - bottomY) / uiElementHeight);
                    vertexList[i] = vertex;
                }

                vh.Clear();

                vh.AddUIVertexTriangleStream(vertexList);
            }
        }
    }
}